package pageProcessor;

import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import main.ServerGlobals;
import protocol.HTTPRequest;
import protocol.HTTPResponse;
import protocol.Headers;
import Servlets.List;
import Servlets.Login;
import Servlets.Logout;
import Servlets.Send;
import Servlets.add_user;
import Servlets.create_Group;
import Servlets.queue;
import Servlets.remove_user;

public class JSP implements PageProcessorInterface {
	private Hashtable<String, PageProcessorInterface> _JSPPages;

	public JSP() {
		_JSPPages = new Hashtable<String, PageProcessorInterface>();
		_JSPPages.put(Login.class.getSimpleName().toLowerCase(), new Login());
		_JSPPages.put(List.class.getSimpleName().toLowerCase(), new List());
		_JSPPages.put(create_Group.class.getSimpleName().toLowerCase(),
				new create_Group());
		_JSPPages.put(add_user.class.getSimpleName().toLowerCase(),
				new add_user());
		_JSPPages.put(remove_user.class.getSimpleName().toLowerCase(),
				new remove_user());
		_JSPPages.put(queue.class.getSimpleName().toLowerCase(), new queue());
		_JSPPages.put(Send.class.getSimpleName().toLowerCase(), new Send());
		_JSPPages.put(Logout.class.getSimpleName().toLowerCase(), new Logout());
	}

	@Override
	public HTTPResponse process(HTTPRequest httpRequest,
			ServerGlobals serverGlobals) {
		String ResultString = null;
		Pattern regex = Pattern.compile("([^/]+)\\.jsp",
				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE
						| Pattern.DOTALL | Pattern.MULTILINE);
		Matcher regexMatcher = regex.matcher(httpRequest
				.getfHTTPHttpRequestHeaders().getfURI());
		if (regexMatcher.find()) {
			ResultString = regexMatcher.group(1);
		}

		if (ResultString == null) {
			return new HTTPResponse(Headers.STATUS_404, Headers.HTTP_VERSION,
					null, "", false);
		}
		if (!this._JSPPages.containsKey(ResultString)) {
			return new HTTPResponse(Headers.STATUS_404, Headers.HTTP_VERSION,
					null, "", false);
		}
		return this._JSPPages.get(ResultString).process(httpRequest,
				serverGlobals);
	}

}
